package src.tree;

import src.LinkedQueue;
import src.LinkedStack;
import src.Queue;
import src.Stack;

/**
 * 二分搜索树
 */
public class BST<E extends Comparable<E>> {

    /**
     * 节点定义
     */
    private class Node{
        public E e;
        public Node left, right;
        public Node(E e){
            this.e = e;
            left = right = null;
        }
    }

    private Node root;
    private int size;

    public BST(){
        root = null;
        size = 0;
    }

    /**
     * @return the size
     */
    public int getSize() {
        return size;
    }

    public boolean isEmpty(){
        return size == 0;
    }

    public void add (E e){
        root = add(root, e);
    }
    /**
     * 递归向二分搜索树插入元素
     * @param node
     * @param e
     * @return
     */
    private Node add(Node node, E e){
        if (node == null) {
            size ++;
            return new Node(e);
        }
        if(e.compareTo(node.e) < 0){
            node.left = add(node.left, e);
        }else if(e.compareTo(node.e) > 0){
            node.right = add(node.right, e);
        }
        return node;
    }

    public boolean contains(E e) {
        return contains(root, e);
    }

    private boolean contains(Node node, E e){
        if (node == null) {
            return false;
        }
        if (e.compareTo(node.e) == 0) {
            return true;
        }else if(e.compareTo(node.e) < 0) {
            return contains(node.left, e);
        }else{
            return contains(node.right, e);
        }
    }
    // 前序遍历
    public void preOrder(){
        preOrder(root);
        System.out.println();
    }
    private void preOrder(Node node){
        if (node == null)
            return ;
        System.out.print(node.e + " ");
        preOrder(node.left);
        preOrder(node.right);
    }
    // 非递归的前序遍历
    public void preOrderNR(){
        Stack<Node> stack = new LinkedStack<>();
        stack.push(root);
        while (! stack.isEmpyt()){
            Node cur = stack.pop();
            System.out.print(cur.e + " ");
            if (cur.right != null) {
                stack.push(cur.right);
            }
            if (cur.left != null) {
                stack.push(cur.left);
            }
        }
        System.out.println();
    }

    // 中序遍历 
    public void order(){
        midOrder(root);
        System.out.println();
    }
    private void midOrder(Node node){
        if(node == null)
            return ;
        midOrder(node.left);
        System.out.print(node.e + " ");
        midOrder(node.right);
    }
    // 后序遍历
    public void postOrder(){
        postOrder(root);
        System.out.println();
    }
    private void postOrder(Node node){
        if (node == null) {
            return ;
        }
        postOrder(node.left);
        postOrder(node.right);
        System.out.print(node.e + " ");
    }

    public void levelOrder() {
        Queue<Node> queue = new LinkedQueue<>();
        queue.enQueue(root);
        while(! queue.isEmpty()){
            Node cur = queue.deQueue();
            System.out.print(cur.e + " ");
            if (cur.left != null) {
                queue.enQueue(cur.left);
            }
            if (cur.right != null) {
                queue.enQueue(cur.right);
            }
        }
        System.out.println();
    }

    public E min(){
        if (root == null) {
            throw new IllegalArgumentException("BST is empty!");
        }
        Node cur = root;
        while(cur.left != null){
            cur = cur.left;
        }
        return cur.e;
    }

    private E min(Node node){
        if (node == null) {
            throw new IllegalArgumentException("BST is empty!");
        }
        Node cur = node;
        while(cur.left != null){
            cur = cur.left;
        }
        return cur.e;
    }

    public E max(){
        if (root == null) {
            throw new IllegalArgumentException("BST is empty!");
        }
        Node cur = root;
        while (cur.right != null) {
            cur = cur.right;
        }
        return cur.e;
    }

    public E removeMin(){
        E ret = min();
        root = removeMin(root);
        return ret;
    }
    private Node removeMin(Node node){
        if (node.left == null) {
            Node rightTree = node.right;
            node.right = null;
            size --;
            return rightTree;
        }
        node.left = removeMin(node.left);
        return node;
    }

    public E removeMax(){
        E ret = max();
        root = removeMax(root);
        return ret;
    }
    private Node removeMax(Node node){
        if (node.right == null) {
            Node leftTree = node.left;
            node.left = null;
            size --;
            return leftTree;
        }
        node.right = removeMax(node.right);
        return node;
    }

    public void remove(E e){
        root = remove(root, e);
    }
    private Node remove(Node node, E e){
        if (node == null) {
            return null;
        }
        if (e.compareTo(node.e) < 0) {
            node.left = remove(node.left, e);
        }else if(e.compareTo(node.e) > 0){
            node.right = remove(node.right, e);
        }else{
            // 待删除的元素是叶子节点（无左子树和右子树）=》 直接删除
            // 待删除的元素是非叶子节点
            //                只有左子树  =》 用左子树根节点替换当前节点
            //                只有右子树  =》 用右子树根节点替换当前节点
            //                既有左子树又有右子树 =》 1.找到右子树的最小节点 2.获取并删除该节点 3.用此节点替换要删除的节点
            if (node.left == null) {
                Node rightTree = node.right;
                node.right = null;
                size --;
                return rightTree;
            }else if(node.right == null){
                Node leftTree = node.left;
                node.left = null;
                size --;
                return leftTree;
            }else{
                E rep = min(node.right);
                node.right = removeMin(node.right);
                node.e = rep;
                return node;
            }
        }
		return node;
    }


    // TODO: 打印出二叉树
    /* 
    public String printbst() {
        StringBuilder res = new StringBuilder();
        int depth = 1;
        Stack mainWork = new LinkedStack<>();
        Stack tempWork = new LinkedStack<>();
        int endFlag = 1;

        while(endFlag){

        }
    } */
    @Override
    public String toString() {
        StringBuilder res = new StringBuilder();
        printBst(root, 0, res);
        return res.toString();
    }

    private String depthStr(int depth){
        StringBuffer res = new StringBuffer();
        for (int i = 0; i < depth; i++) {
            res.append("--");
        }
        return res.toString();
    }

    private void printBst(Node node, int depth, StringBuilder s){
        if(node == null)
            return ;
        
        s.append(depthStr(depth) + node.e + "\n");
        printBst(node.left, depth + 1, s);
        printBst(node.right, depth + 1, s);
    }

}